package com.zsrd.self.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.notification.Notification;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationHandler;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationRequest;
import com.zsrd.self.SelfApplication;
import com.zsrd.self.base.Result;
import com.zsrd.self.base.config.*;
import com.zsrd.self.base.controller.BaseController;
import com.zsrd.self.base.vo.SmReturnVo;
import com.zsrd.self.entity.OrderDiscounts;
import com.zsrd.self.entity.SelfUser;
import com.zsrd.self.service.SelfUserService;
import com.zsrd.self.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;


@CrossOrigin
@RestController
@RequestMapping("/api/wx-pay")
@Api(tags = "网站微信支付API")
@Slf4j
public class WxPayController extends BaseController {

    @Autowired
    private SelfUserService selfUserService;

    @Resource
    private WxPayService wxPayService;


    @ApiOperation("调用统一下单API，生成预支付交易会话标识")
    @PostMapping("/jsapi")
    public Result jsapiPay(@RequestBody OrderDiscounts orderDiscounts) throws Exception {
        log.info("发起支付请求");
        Map<String, Object> map = wxPayService.jsapiPay(orderDiscounts);
        return Result.success(map);
    }

    @ApiOperation("微信支付回调")
    @PostMapping("/jsapi/notifyes")
    public Result jsapiNotifys(HttpServletRequest request, HttpServletResponse res) {
        Map<String, Object> map = new HashMap<>();
        try {
            BufferedReader br = request.getReader();
            String str = null;
            StringBuilder sb = new StringBuilder();
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            // 构建request，传入必要参数
            NotificationRequest requests = new NotificationRequest.Builder()
                    .withSerialNumber(request.getHeader("Wechatpay-Serial"))
                    .withNonce(request.getHeader("Wechatpay-Nonce"))
                    .withTimestamp(request.getHeader("Wechatpay-Timestamp"))
                    .withSignature(request.getHeader("Wechatpay-Signature"))
                    .withBody(String.valueOf(sb))
                    .build();
            //验签
            NotificationHandler handler = new NotificationHandler(WXPaySignatureCertificateUtil.getVerifier(), WxV3PayConfig.apiV3Key.getBytes(StandardCharsets.UTF_8));
            //解析请求体
            Notification notification = handler.parse(requests);
            String decryptData = notification.getDecryptData();
            //解析
            JSONObject jsonObject = JSONObject.parseObject(decryptData);
            //支付状态交易状态，枚举值： SUCCESS：支付成功 REFUND：转入退款 NOTPAY：未支付 CLOSED：已关闭 REVOKED：已撤销（付款码支付）
            // USERPAYING：用户支付中（付款码支付） PAYERROR：支付失败(其他原因，如银行返回失败)
            String trade_state = String.valueOf(jsonObject.get("trade_state"));
            if (trade_state.equals("SUCCESS")) {
                //订单号
                String orderNumber = String.valueOf(jsonObject.get("out_trade_no"));
                //微信支付微信生成的订单号
                String transactionId = String.valueOf(jsonObject.get("transaction_id"));
                //省略查询订单

                LambdaQueryWrapper<OrderDiscounts> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(OrderDiscounts::getOrderNo, orderNumber);
                OrderDiscounts one = wxPayService.getOne(wrapper);
                if (one != null) {
                    one.setCode("2");
                    wxPayService.updateById(one);
                } else {
                    return Result.error("未有此订单号");
                }

                //此处处理业务
                map.put("code", "SUCCESS");
                map.put("message", "成功");
                //消息推送成功
                return Result.success(map);
            }
            map.put("code", "RESOURCE_NOT_EXISTS");
            map.put("message", "订单不存在");
            return Result.success(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("code", "FAIL");
        map.put("message", "失败");
        return Result.success(map);
    }


    @ApiOperation("微信支付回调")
    @PostMapping("/jsapi/notify")
    public Result jsapiNotify(@RequestBody OrderDiscounts orderDiscounts) {
        LambdaQueryWrapper<OrderDiscounts> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDiscounts::getOrderNo, orderDiscounts.getOrderNo());
        OrderDiscounts one = wxPayService.getOne(wrapper);
        if (one != null) {
            one.setCode("2");
            wxPayService.updateById(one);
            //抖音回调接口
            QueryWrapper<SelfUser> queryWrapper = new QueryWrapper();
            queryWrapper.eq("official_id", one.getOpenId());
            SelfUser user = selfUserService.getOne(queryWrapper);
            if (user != null) {
                String clickid = user.getClickid();
                if (clickid != null && one.getIsCoupons()==0) {
                    String url = "https://analytics.oceanengine.com/api/v2/conversion";
                    try {
                        HttpClient client = HttpClients.createDefault(); // 构建一个Client
                        HttpPost post = new HttpPost(url); // 构建一个Post请求
                        post.setHeader("Content-Type", "application/json"); // 设置请求头为JSON

                        // 创建一个 JSON 格式的请求主体
                        JSONObject jsonRequest = new JSONObject();
                        jsonRequest.put("event_type", "active_pay");
                        jsonRequest.put("timestamp", new Date().getTime());
                        JSONObject context = new JSONObject();
                        JSONObject ad = new JSONObject();
                        ad.put("callback", clickid);
                        context.put("ad", ad);
                        jsonRequest.put("context", context);
                        StringEntity input = new StringEntity(jsonRequest.toString(), "UTF-8");
                        post.setEntity(input);

                        HttpResponse response = client.execute(post); // 提交POST请求
                        HttpEntity result = response.getEntity(); // 拿到返回的HttpResponse的"实体"
                        String content = EntityUtils.toString(result);
                        // 返回JSON格式的响应字符串
                    } catch (Exception e) {
                        e.printStackTrace();
                        // 返回错误信息
                    }
                }
            }
        } else {
            return Result.error("未有此订单号");
        }
        return Result.success("支付成功");
    }


    @GetMapping("/aaa")
    public String aaa() {
        //抖音回调接口
        QueryWrapper<SelfUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("official_id", "od-O_6a8jcKcJVLNLnVfR5o2QDCc");
        SelfUser user = selfUserService.getOne(queryWrapper);
        if (user != null) {
            String clickid = user.getClickid();
            if (clickid != null) {
                String url = "https://analytics.oceanengine.com/api/v2/conversion";
                try {
                    HttpClient client = HttpClients.createDefault(); // 构建一个Client
                    HttpPost post = new HttpPost(url); // 构建一个Post请求
                    post.setHeader("Content-Type", "application/json"); // 设置请求头为JSON

                    // 创建一个 JSON 格式的请求主体
                    JSONObject jsonRequest = new JSONObject();
//                    jsonRequest.put("event_type", "customer_effective");
                    jsonRequest.put("event_type", "active_pay");
                    jsonRequest.put("timestamp", new Date().getTime());
                    JSONObject context = new JSONObject();
                    JSONObject ad = new JSONObject();
                    ad.put("callback", clickid);
                    context.put("ad", ad);
                    jsonRequest.put("context", context);
                    StringEntity input = new StringEntity(jsonRequest.toString(), "UTF-8");
                    post.setEntity(input);

                    HttpResponse response = client.execute(post); // 提交POST请求
                    HttpEntity result = response.getEntity(); // 拿到返回的HttpResponse的"实体"
                    String content = EntityUtils.toString(result);
                    // 返回JSON格式的响应字符串
                    return content;
                } catch (Exception e) {
                    e.printStackTrace();
                    // 返回错误信息
                    return "{\"error\": \"" + e.getMessage() + "\"}";
                }
            }
        }
        return "";
    }


    /**
     * 读取微信支付信息
     *
     * @param request 信息
     * @return 结果
     */
    private static String readData(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            StringBuilder result = new StringBuilder();
            br = request.getReader();
            for (String line; (line = br.readLine()) != null; ) {
                if (result.length() > 0) {
                    result.append("\n");
                }
                result.append(line);
            }
            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation("获取随机免减大于0小于2")
    @PostMapping("/round")
    private double round() {
        // 生成大于0小于等于2的随机double数字并保留两位小数
        Double randomDouble = Math.random() * 2; // 生成大于0小于等于2的随机double数字
        randomDouble = Math.round(randomDouble * 100.0) / 100.0; // 保留两位小数
        return randomDouble;
    }


    @ApiOperation("获取code")
    @GetMapping("getCode")
    private Result round(@RequestParam String code) {
        Map<String, Object> code1 = wxPayService.getCode(code);
        return Result.success(code1);
    }


    @GetMapping("getConfig")
    private Result getConfig(@RequestParam String url) throws Exception {
        Map<String, String> sign = JsSignUtil.sign(url);
        return Result.success(sign);
    }


}
